//
//  AppDelegate+extension.m
//  SquashSpark
//
//  Created by Coollang on 2017/10/25.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "AppDelegate+extension.h"
#import <Realm/Realm.h>
#import "MyNavigationViewController.h"
#import "YFLoginViewController.h"
#import "YFMMDrawerStateManager.h"
#import "UnityAppController.h"
#import "YFLoginHelper.h"
#import "YFGuideFirstController.h"
#import "JCTabBarViewController.h"


@implementation AppDelegate (extension)

//配置数据库
- (void)migrationRealm {
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
    // 设置新的架构版本。这个版本号必须高于之前所用的版本号（如果您之前从未设置过架构版本，那么这个版本号设置为 0）
    config.schemaVersion = 3;
    config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
        // 什么都不要做！Realm 会自行检测新增和需要移除的属性，然后自动更新硬盘上的数据库架构
        if (oldSchemaVersion < 1) {
            
        }
    };
    [RLMRealmConfiguration setDefaultConfiguration:config];
    [RLMRealm defaultRealm];
}

/**
 unity3D配置
 */
- (void)setupUnity3DForApplication:(UIApplication *)application
     didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.unityController = [[UnityAppController alloc] init];
    [self.unityController application:application didFinishLaunchingWithOptions:launchOptions];
    UnityGetMainWindow().hidden = YES;
}


+ (void)logoutWithShowLoginVC:(BOOL)isShowLoginVc {
    [[YFCommunicationManager shareInstance] disconnectThePeripheralWithCompletionBlock:nil];
    [[YFNetworkingService sharedInstance] configureBaseUrl];
    [YFUserDefaults setAutoLogin:NO];
    MyNavigationViewController *nav = [[UIStoryboard storyboardWithName:@"Login" bundle:nil] instantiateInitialViewController];
    AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appdelegate.window.rootViewController presentViewController:nav animated:YES completion:nil];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        MyNavigationViewController *navT = [[UIStoryboard storyboardWithName:@"Login" bundle:nil] instantiateInitialViewController];
        if (isShowLoginVc) {
            for (UIViewController *vc in navT.viewControllers) {
                if ([vc isKindOfClass:[YFLoginViewController class]]) {
                    YFLoginViewController *loginvc = (YFLoginViewController *)vc;
                    loginvc.view.userInteractionEnabled = NO;
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        loginvc.view.userInteractionEnabled = YES;
                        [loginvc comeInLoginInOrLogupVc:kLoginIn];
                    });
                    break;
                }
            }
        }
        [nav dismissViewControllerAnimated:NO completion:^{
            [YFMMDrawerStateManager sharedManager].drawerController = nil;
        }];
        appdelegate.window.rootViewController = navT;
    });
    
}

- (void)setUpWindow {
     BOOL isNeedWelcome = [YFUserDefaults isNeedGuideView];
     BOOL isHaveLogin = [YFUserDefaults shouldAutoLogin];
    
     self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
     self.window.backgroundColor = [UIColor whiteColor];
     self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    if (isHaveLogin) {
        // 刷新登录
//        self.window.rootViewController = [[YFMMDrawerStateManager sharedManager] FetchDrawerController];
        self.window.rootViewController = [JCTabBarViewController new];
        // 获取用户信息
        [YFLoginHelper getuserInfoItemCompleted:^(NSError *error) {
            
        }];
    }else {
        self.window.rootViewController = [[UIStoryboard storyboardWithName:@"Login" bundle:nil] instantiateInitialViewController];
        if (isNeedWelcome) {
            __weak typeof(self) weakSelf = self;
            YFGuideFirstController *guideVc = [[YFGuideFirstController alloc] initWithNibName:@"YFGuideFirstController" bundle:nil];
            self.guideFirstVc = guideVc;
            guideVc.view.frame = self.window.bounds;
            [self.window addSubview:guideVc.view];
            
            [guideVc setSignButtonClickBlock:^(kLoginType loginType) {
                [UIView animateWithDuration:0.35 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                    weakSelf.guideFirstVc.view.alpha = 0;
                } completion:^(BOOL finished) {
                    [weakSelf.guideFirstVc.view removeFromSuperview];
                    weakSelf.guideFirstVc = nil;
                    MyNavigationViewController *loginNav = (MyNavigationViewController *)weakSelf.window.rootViewController;
                   YFLoginViewController *loginVc = loginNav.viewControllers.firstObject;
                    [loginVc comeInLoginInOrLogupVc:loginType];
                }];
            }];
        }
    }
    [self.window makeKeyAndVisible];
    
    self.startImageView = [[UIImageView alloc] initWithFrame:self.window.bounds];
    self.startImageView.image = [UIImage imageNamed:@"guide_home"];
    WSProgressHUD *hud = [WSProgressHUD showOnView:self.startImageView andString:@""];
    [hud showWithMaskType:WSProgressHUDMaskTypeClear];
    [self.window addSubview:self.startImageView];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [hud dismiss];
        [hud removeFromSuperview];
        if (isHaveLogin ) {
            UIBezierPath *endMaskPath =  [UIBezierPath bezierPathWithArcCenter:CGPointMake(0, 0) radius:0.5 startAngle:0 endAngle:2*M_PI clockwise:YES];
            UIBezierPath *startMaskPath =  [UIBezierPath bezierPathWithArcCenter:CGPointMake(0, 0) radius:2*kYFScreenHeight startAngle:0 endAngle:2*M_PI clockwise:YES];
            CAShapeLayer *maskLayer = [CAShapeLayer layer];
            maskLayer.path = endMaskPath.CGPath;
            self.startImageView.layer.mask = maskLayer;
            CABasicAnimation *maskLayerAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
            maskLayerAnimation.fromValue = (__bridge id)(startMaskPath.CGPath);
            maskLayerAnimation.toValue = (__bridge id)((endMaskPath.CGPath));
            maskLayerAnimation.duration = 0.8;
            maskLayerAnimation.timingFunction = [CAMediaTimingFunction  functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
            [maskLayer addAnimation:maskLayerAnimation forKey:@"path"];
            maskLayerAnimation.delegate = self;
        }else {
            [self.startImageView removeFromSuperview];
            self.startImageView = nil;
            if (self.guideFirstVc) {
                [self.window bringSubviewToFront:self.guideFirstVc.view];
            }
        }
    });

}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    [self.startImageView removeFromSuperview];
    self.startImageView = nil;
}


@end
